package com.shuoyue.ycgk.ui.estimate;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.Estimate;
import com.shuoyue.ycgk.entity.UserTestPaper;
import com.shuoyue.ycgk.ui.questionbank.practice.estamate.EstamateQuestionActivity;
import com.shuoyue.ycgk.utils.ShareUtil;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EstimateScoreActivity extends BaseMvpActivity<EstimateContract.Presenter>
        implements EstimateContract.View {

    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    ListWithPage listWithPage;


    Handler handler = new Handler();
    Runnable task = new Runnable() {
        @Override
        public void run() {
            adapter.notifyDataSetChanged();
            handler.postDelayed(task, 1000);
        }
    };

    public static void start(Context context, int subjectId) {
        context.startActivity(new Intent(context, EstimateScoreActivity.class)
                .putExtra("id", subjectId));
    }

    EstimateAdapter adapter;
    int subjectId;

    boolean isFistGetData = true;//是否首次加载数据

    boolean isEnableListClick = true;//是否禁止点击列表，由于答案提交后台异步，有延迟，在刷新数据之前避免再次进入答题，下次刷新前不允许点击

    /**
     * 初始化layouy
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_estimate_score;
    }

    /**
     * 初始化布局
     */
    @Override
    protected void initView() {
        pageTitle.setText("考试估分");
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setImageResource(R.mipmap.share);

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            mPresenter.getEsList(subjectId, 1);
            refreshLayout.finishRefresh();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            mPresenter.getEsList(subjectId, listWithPage.getCurrent() + 1);
            refreshLayout.finishLoadMore();
        });
        recycleView.setLayoutManager(new LinearLayoutManager(mContext));
        recycleView.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 8), false));
        adapter = new EstimateAdapter(null);
        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            Estimate estimate = (Estimate) adapter.getItem(position);
            if (!isEnableListClick) {
                return;
            }
            if (estimate.getIsSign() == 1) {
                //已报名，根据状态进入答题
                if (estimate.getStatus() == 0) {
                    //未交卷的
                    if (estimate.getActionStatus() == 2) {
                        EsSelecctJobActivity.start(mContext, estimate.getId(), estimate.getTestId(), estimate.getMemberEvaId(),estimate.getTitle());
                    } else {
                        toast("不在考试时间内，请注意考试时间");
                    }
                } else {
                    EsSourtActivity.start(mContext, estimate.getEvaId(), estimate.getTestId(),estimate.getTitle());
                }

            } else if (estimate.getIsSign() == 0 && estimate.getActionStatus() != 3) {
                //未报名并且没有结束的，去报名
//                EsSelecctJobActivity.start(mContext, estimate.getId());
                mPresenter.registTest(estimate.getId());
            }
        });
        recycleView.setAdapter(adapter);
//        registSimpleTextEmptyView(adapter, "暂无估分考试");
        registEmptyViewWrapHeight(adapter, "暂无估分考试");
        handler.postDelayed(task, 1000);
    }

    @Override
    public void initData() {
        super.initData();
        subjectId = getIntent().getIntExtra("id", -1);
        mPresenter = new EstimateContract.Presenter();
        mPresenter.attachView(this);
    }

    Runnable refreshTask = new Runnable() {
        @Override
        public void run() {
            mPresenter.getEsList(subjectId, 1);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
//        if (isFistGetData) {
//            mPresenter.getEsList(subjectId, 1);
//            isFistGetData = false;
//        } else {
//            //后台异步操作，等待一会再刷新结果
//            handler.postDelayed(refreshTask, 100);
//        }
        mPresenter.getEsList(subjectId, 1);
    }

    @OnClick(R.id.back)
    public void onViewClicked() {
    }

    @Override
    public void getEsListSuc(ListWithPage<Estimate> list) {
        isEnableListClick = true;
        listWithPage = list;
        if (list.getCurrent() == 1) {
            adapter.resetData(list.getRecords());
        } else {
            adapter.addData(list.getRecords());
        }
        refreshLayout.setEnableLoadMore(list.getCurrent() != list.getPages() && list.getPages() > 0);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void getPaperSuc(UserTestPaper userTestPaper) {
        isEnableListClick = false;//不允许点击
        EstamateQuestionActivity.start(mContext, userTestPaper, 0, userTestPaper.getTag());
    }

    @Override
    public void registSuc() {
        mPresenter.getEsList(subjectId, 1);
    }


    @OnClick({R.id.back, R.id.his, R.id.iv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.his:
                startActivity(new Intent(mContext, EstimateHisActivity.class).putExtra("id", subjectId));
                break;
            case R.id.iv_right:
                ShareUtil.shareUrl(this, ShareUtil.QUESTION_URL + subjectId,
                        "考试估分", null, null);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(task);
        handler.removeCallbacks(refreshTask);

    }
}
